package ua.khpi.si.kit49.diploma.db.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ua.khpi.si.kit49.diploma.db.dto.City;
import ua.khpi.si.kit49.diploma.db.dto.Connection;

/**
 * Implementation of Connection dao
 * 
 * @author netstalk3r
 * 
 */
@Repository("connectionDAO")
public class ConnectionDAOImpl implements ConnectionDAO {

	// /////////////////
	// Queries
	// ////////////////
	private static final String QUERY_GET_ALL_CONNECTIONS = "FROM Connection";
	private static final String QUERY_GET_CONNECTION_BY_ID = "FROM Connection WHERE id = :id";
	private static final String QUERY_GET_CONNECTION_BY_START_AND_FINISH = "FROM Connection WHERE cityStart = :cityStart AND cityFinish = :cityFinish";

	@Autowired(required = true)
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	@Override
	public List<Connection> getAllConnection() {
		return sessionFactory.getCurrentSession()
				.createQuery(QUERY_GET_ALL_CONNECTIONS).list();
	}

	@Override
	public Connection getConnectionById(Integer id) {
		return (Connection) sessionFactory.getCurrentSession()
				.createQuery(QUERY_GET_CONNECTION_BY_ID).setParameter("id", id)
				.uniqueResult();
	}

	@Override
	public Connection getConnectionByStartAndFinish(City start, City finish) {
		return (Connection) sessionFactory.getCurrentSession()
				.createQuery(QUERY_GET_CONNECTION_BY_START_AND_FINISH)
				.setParameter("cityStart", start)
				.setParameter("cityFinish", finish).uniqueResult();
	}

}
